package com.taylor.community.controller.interceptor;

import com.taylor.community.entity.User;
import com.taylor.community.service.DataService;
import com.taylor.community.util.HostHolder;
import org.apache.catalina.Host;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 由于每次请求都需要统计UV或者是DAU 所以通过拦截器
 * @author 26925
 */
@Component
public class DataInterceptor implements HandlerInterceptor {
    @Autowired
    private DataService dataService;
    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //存Uv
        String ip = request.getRemoteHost();
        dataService.recordUv(ip);
        //存Dau
        User user = hostHolder.getUser();
        if(user!=null){
            dataService.recordDau(user.getId());
        }
        return true;
    }

}
